import { IScript } from './commlib.interfaces';

export class Util {
  /**
   * Adding a library to the runtime global scope
   * addGlobalScripts
   * @param scriptsConfig IScript[]
   * @param callback once it ready.
   */
  public static addGlobalScripts(scriptsConfig: IScript[], callback: any) {
    // TODO： we need to support multiple scripts in the future
    if (
      scriptsConfig.length > 0 &&
      typeof document !== 'undefined' &&
      scriptsConfig[0].url &&
      scriptsConfig[0].url.trim()
    ) {
      const script = document.createElement('script');
      script.src = scriptsConfig[0].url;
      script.onload = callback;
      document.body.appendChild(script);
    } else {
      callback();
    }
  }

  public static convertToJsonObject(object: any): any {
    if (!object) {
      return null;
    }

    try {
      JSON.parse(object);
    } catch (e) {
      return null;
    }
  }
}
